"use strict";

const Controller = require("egg").Controller;

class AdminController extends Controller {
  async login() {
    const { ctx, app, service } = this;
    const { email, password } = ctx.request.body;
    const rules = {
      email: { type: "email" },
      password: { type: "password" },
    };
    ctx.validate(rules);
    const result = await service.admin.verify({ email, password });
    const now = new Date().getTime();
    const tokenTime = 1000 * 60 * 60 * 24 * 30; //token可用时长毫秒
    const token = app.jwt.sign(
      {
        userId: result.id,
        exp: parseInt((now + tokenTime) / 1000),
      },
      app.config.jwt.secret
    );
    ctx.body = {
      success: true,
      msg: "查询成功",
      data: result,
      token,
    };

  }
  async register() {
    const { ctx, service } = this;
    const { nickname, email, password } = ctx.request.body;
    const rules = {
      nickname: { type: "string", min: 3, max: 20 },
      email: { type: "email" },
      password: { type: "password" },
    };
    ctx.validate(rules);
    const result = await service.admin.create({
      nickname,
      email,
      password,
    });
    ctx.success("创建成功", result);
  }
}

module.exports = AdminController;
